do "usa_00058.do"

use "full1850_raw",clear
keep if gq~=3 & gq~=4

gen constant = 1
gen farmer = occ1950 == 100
gen age15plus = age>=15

#delimit cr	

*Merge with Eckert crosswalk
rename stateicp icpsrst 
rename countyicp icpsrcty
	
joinby icpsrst icpsrcty using "EGLP_1850.dta", unmatched(both)

rename _merge merge1850crosswalk

gen cty_fips = nhgisst_1990*100 + (nhgiscty_1990/10)

gen VAcounties = cty_fips==51177|cty_fips==51165|cty_fips==51121|cty_fips==51053

*For the VA counties replace the county fips of the surrounding county as the county of the independent city
*This will keep those records when merge to Normal Asylum counties

replace cty_fips = 51730 if cty_fips==51053
replace cty_fips = 51750 if cty_fips==51121
replace cty_fips = 51630 if cty_fips==51177
replace cty_fips = 51660 if cty_fips==51165

*Drop non-merged from crosswalk
drop if merge1850crosswalk==2 & VAcounties~=1

drop if merge1850crosswalk==1

rename cty_fips cty_fips1850

tostring cty_fips1850, gen(cty_fipstr)
gen statefip1850 = substr(cty_fipstr, 1,1) if length(cty_fipstr)==4
replace statefip1850 = substr(cty_fipstr, 1, 2) if length(cty_fipstr)==5
destring statefip1850, replace

tab icpsrst if statefip1850==.

#delimit cr
*Drop states that were not yet states on Census Day 1850: 

#delimit ;
drop if statefip1850==6|statefip1850==27|statefip1850==38|statefip1850==46|statefip1850==49|statefip==4|
statefip==8|statefip==16|statefip==30|statefip==31|statefip==32|statefip==35|statefip==40|
statefip==41|statefip==53|statefip==54|statefip==56;

#delimit cr

tab statefip
*Multiply by weights based on crosswalk
local vars constant realprop age15plus farmer
foreach x of local vars{
gen `x'wt = `x'*weight
drop `x'
rename `x'wt `x'
}

*Collapse by cty_fips based on sums

#delimit ;
collapse (sum) constant realprop farmer age15plus (mean) statefip1850, by(cty_fips1850);

#delimit cr

rename constant ctypop1850
gen realproppc = realprop/ctypop1850
gen pctfarmer = farmer/age15plus
 
save "ctychars_1850.dta", replace



